<script setup>
import { ref, h, getCurrentInstance, watch, reactive } from 'vue';
import { UnorderedListOutlined, AppstoreOutlined, UserOutlined, ShoppingCartOutlined } from '@ant-design/icons-vue';
import md5 from 'md5-node';
import { reset_psd, getUserInfo } from '@/apis/user/user';
import { Modal, message } from 'ant-design-vue';

import { useUserInfo } from '@/store/useUserInfo';
const user = useUserInfo()
const vm = getCurrentInstance()
const current = ref(['Home']);
const items = ref([
  {
    key: 'Home',
    icon: () => h(AppstoreOutlined),
    label: '首页',
    title: '首页',
  },
  {
    key: 'Product',
    icon: () => h(UnorderedListOutlined),
    label: '商品列表',
    title: '商品列表',
  },
  {
    key: 'Car',
    icon: () => h(ShoppingCartOutlined),
    label: '我的购物车',
    title: '我的购物车',
  },
  {
    key: 'Order',
    icon: () => h(ShoppingCartOutlined),
    label: '我的订单',
    title: '我的订单',
  },
  {
    key: 'Profile',
    icon: () => h(UserOutlined),
    label: '个人信息',
    title: 'Navigation Two',
  },
])

watch(() => vm.proxy.$route, (curr) => {
  current.value = [curr.name];
}, {
  immediate: true
})

function init() {
  if (!user.isLogin) {
    getUserInfo().then(res => {
      if (res.code === 0) {
        user.setUserInfo(res.data);
      }
    })
  }
}
init();

const selectEvent = (d) => {
  if (!user.isLogin && (d.key === 'Car' || d.key === 'Order' || d.key === 'Profile')) {
    Modal.confirm({
      title: '你尚未登录，请先登录用户！',
      content: '',
      centered: true,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        vm.proxy.$router.push({
          name: 'UserLogin',
        })
      }
    });
    return;
  }
  vm.proxy.$router.push({
    name: d.key
  })
}


const formRef = ref();
const visible = ref(false);
const confirmLoading = ref(false);

const formState = reactive({
  newPsd: '',
  confirmPsd: ''
});

// 密码验证函数
const validatePsd = (value) => {
  const reg = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,12}$/;
  return reg.test(value);
};

// 表单验证规则
const rules = {
  newPsd: [
    { required: true, message: '请输入密码' },
    {
      validator: (_, value) => {
        if (!validatePsd(value)) {
          return Promise.reject('密码6-12位由数字和字母组成');
        }
        return Promise.resolve();
      }
    }
  ],
  confirmPsd: [
    { required: true, message: '请再次输入密码' },
    {
      validator: (_, value) => {
        if (value !== formState.newPsd) {
          return Promise.reject('两次输入密码不一致，请重新输入！');
        }
        return Promise.resolve();
      }
    }
  ]
};

const showModal = () => {
  visible.value = true;
};

const handleOk = async () => {
  try {
    confirmLoading.value = true;
    await formRef.value.validate();

    const params = {
      confirmPsd: md5(formState.confirmPsd),
      password: md5(formState.newPsd),
    };

    const res = await reset_psd(params);
    message.success(res.message);
    visible.value = false;
    formRef.value.resetFields();
    user.setUserInfo({});
    sessionStorage.setItem('token', '');
    vm.proxy.$router.push({
      name: 'UserLogin',
    })
  } catch (error) {
    console.error('密码修改失败:', error);
  } finally {
    confirmLoading.value = false;
  }
};

const handleCancel = () => {
  formRef.value.resetFields();
  visible.value = false;
};
const handleDropdown = (e) => {
  if (e.key === 'updatePwd') {
    showModal();
  } else if (e.key === 'exit') {
    Modal.confirm({
      title: '退出登录',
      content: '你确定要退出登录吗？',
      centered: true,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        user.setUserInfo({});
        sessionStorage.setItem('token', '');
        vm.proxy.$router.push({
          name: 'UserLogin',
        })
        message.success('退出登录成功！')
      }
    });
  } else if (e.key === 'goAdmin') {
    vm.proxy.$router.push({
      name: 'AdminUser',
    })
  }
}

</script>


<template>
  <a-layout class="layout">
    <a-layout-header>
      <div class="header">
        <div class="header-left">
          <div class="logo-container">
            <img class="logo" src="../assets/eat-quickly.png" alt="">
            <span>基于Vue3的外卖管理系统</span>
          </div>
          <a-menu v-model:selectedKeys="current" theme="dark" mode="horizontal" :style="{ lineHeight: '64px' }"
            :items="items" @select="selectEvent" />
        </div>
        <div class="header-right">
          <a-dropdown :trigger="['click']" v-if="user.isLogin">
            <div style="color: #fff;display: flex;align-items: center;">
              <a-avatar>
                <template #icon>
                  <a-avatar :src="user.userInfo.avatar" />
                </template>
              </a-avatar>
              <span style="padding-left: 10px;">{{ user.userInfo.nickname }}</span>
            </div>
            <template #overlay>
              <a-menu @click="handleDropdown">
                <a-menu-item key="goAdmin">进入后台系统</a-menu-item>
                <a-menu-item key="updatePwd">修改密码</a-menu-item>
                <a-menu-item key="exit">退出登录</a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </div>
    </a-layout-header>
    <a-layout-content style="height: 100%;padding:20px 10%;overflow: auto;">
      <RouterView style="height: 100%;" />
    </a-layout-content>
  </a-layout>
  <a-modal v-model:visible="visible" title="修改密码" width="500px" centered>
    <a-form ref="formRef" :model="formState" :rules="rules" layout="vertical">
      <a-form-item label="新的密码" name="newPsd">
        <a-input-password v-model:value="formState.newPsd" placeholder="请输入密码" />
      </a-form-item>
      <a-form-item label="确认密码" name="confirmPsd">
        <a-input-password v-model:value="formState.confirmPsd" placeholder="请再次输入密码" />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button key="back" @click="handleCancel">取 消</a-button>
      <a-button key="submit" type="primary" :loading="confirmLoading" @click="handleOk">确 定</a-button>
    </template>
  </a-modal>
</template>

<style lang="less" scoped>
.layout {
  height: 100%;
}

.site-layout-background {
  background: #fff;
}

.ant-layout-header {
  padding: 0;

  .header {
    display: flex;
    justify-content: space-between;

    .header-left {
      display: flex;

      .logo-container {
        padding: 0 20px;
        font-size: 20px;
        color: #fff;
        font-weight: bold;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .logo {
        width: 40px;
        height: 40px;
        margin-right: 10px;
      }
    }

    .header-right {
      padding-right: 20px;
    }
  }


}
</style>